package com.sy.blog.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sy.blog.dao.pojo.SysUser;
import com.sy.blog.service.LoginService;
import com.sy.blog.service.SysUserService;
import com.sy.blog.utils.JWTUtils;
import com.sy.blog.vo.ErrorCode;
import com.sy.blog.vo.LoginUserVo;
import com.sy.blog.vo.Result;
import com.sy.blog.vo.params.LoginParams;
import org.apache.commons.codec.cli.Digest;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.TimeoutUtils;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.TimeUnit;


@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    private static final String salt = "SY#";

    /**
     * 1、检验传入的参数是否合法
     * 2、合法的话去数据库查询对应的User是否存在
     * 3、存在的话返回token，不存在则登录失败
     * 4、将登录成功后的token给放到redis中， token-User 时间
     *
     * @return
     */
    @Override
    public Result login(LoginParams loginParams) {
        // 获取账号密码
        String account = loginParams.getAccount();
        String password = loginParams.getPassword();
        // 检验是否为空
        if (StringUtils.isBlank(account) || StringUtils.isBlank(password)) {
            return Result.fail(ErrorCode.PARAMS_ERROR.getCode(), ErrorCode.PARAMS_ERROR.getMsg());
        }

        // md5密码加密
        password = DigestUtils.md5Hex(password + salt);

        // 查询账号和密码是否有对应的用户
        SysUser sysUser = sysUserService.findUser(account, password);

        if (sysUser == null) {
            return Result.fail(ErrorCode.ACCOUNT_PWD_NOT_EXIST.getCode(), ErrorCode.ACCOUNT_PWD_NOT_EXIST.getMsg());
        }

        // 说明查到了，即登录成功，返回给客户端一个token
        String token = JWTUtils.createToken(sysUser.getId());

        redisTemplate.opsForValue().set("Token_" + token, JSON.toJSONString(sysUser), 1, TimeUnit.DAYS);

        return Result.success(token);

    }


    /**
     * 检验前端传入的token是否合法
     *
     * @param token
     * @return
     */
    @Override
    public SysUser checkToken(String token) {
        if (StringUtils.isBlank(token)) {
            return null;
        }

        Map<String, Object> map = JWTUtils.checkToken(token);
        if (map == null) {
            return null;
        }

        String loginUser = redisTemplate.opsForValue().get("Token_" + token);
        if (StringUtils.isBlank(loginUser)) {
            return null;
        }
        // 解析Json数据
        SysUser sysUser = JSON.parseObject(loginUser, SysUser.class);

        return sysUser;

    }

    /**
     * 删除服务器端redis中的token信息即可
     *
     * @param token
     * @return
     */
    @Override
    public Result loginOut(String token) {
        redisTemplate.delete("Token_" + token);
        return Result.success(null);
    }


    /**
     * 1、检验参数合法性
     * 2、判断数据库中是否存在该用户
     * 3、保存该用户
     * 4、生成token并放入redis中
     *
     * @param loginParam
     * @return
     */
    @Override
    public Result register(LoginParams loginParam) {
        // 合法性：非空
        String account = loginParam.getAccount();
        String password = loginParam.getPassword();
        String nickname = loginParam.getNickname();
        if (StringUtils.isBlank(account)
                || StringUtils.isBlank(password)
                || StringUtils.isBlank(nickname)
        ) {
            return Result.fail(ErrorCode.PARAMS_ERROR.getCode(), ErrorCode.PARAMS_ERROR.getMsg());
        }

        // 判断是否注册
        SysUser sysUser = sysUserService.findUserByAccount(account);
        if (sysUser != null) {
            return Result.fail(ErrorCode.ACCOUNT_EXIST.getCode(), ErrorCode.ACCOUNT_EXIST.getMsg());
        }

        // 保存数据到数据库
        sysUser = new SysUser();
        sysUser.setNickname(nickname);
        sysUser.setAccount(account);
        sysUser.setPassword(DigestUtils.md5Hex(password + salt));
        sysUser.setCreateDate(System.currentTimeMillis());
        sysUser.setLastLogin(System.currentTimeMillis());
        sysUser.setAvatar("/static/img/logo.b3a48c0.png");
        sysUser.setAdmin(1); //1 为true
        sysUser.setDeleted(0); // 0 为false
        sysUser.setSalt("");
        sysUser.setStatus("");
        sysUser.setEmail("");
        this.sysUserService.save(sysUser);

        //token
        String token = JWTUtils.createToken(sysUser.getId());

        redisTemplate.opsForValue().set("Token_" + token, JSON.toJSONString(sysUser), 1, TimeUnit.DAYS);
        return Result.success(token);
    }

}
